package com.simpleim.starter.processor;

import com.simpleim.im.common.bean.msg.ProtoMsg;
import com.simpleim.starter.protoBuilder.ChatMsgBuilder;
import com.simpleim.starter.server.ServerSession;
import com.simpleim.starter.server.SessionMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ChatRedirectProcesser extends AbstractServerProcesser{

    private static final Logger LOGGER = LoggerFactory.getLogger(ChatRedirectProcesser.class);

    @Autowired
    private ChatMsgBuilder msgBuilder;

    @Override
    public ProtoMsg.HeadType type() {
        return ProtoMsg.HeadType.MESSAGE_REQUEST;
    }

    @Override
    public boolean action(ServerSession session, ProtoMsg.Message message) {
        ProtoMsg.MessageRequest chatMsg = message.getMessageRequest();

        String to= chatMsg.getTo();
        List<ServerSession> list = SessionMap.inst().getSessionsBy(to);
        if (list.isEmpty()) {
            LOGGER.error("发送的目标没有登录：{}", to);
            return false;
        }
        // 循环发送消息即可
        for (ServerSession serverSession : list) {
            if (serverSession != null && serverSession.isLogin()) {
                serverSession.writeAndFlush(message);
            }
        }
        return true;
    }
}
